<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js" type="text/javascript"></script>
  <style>
    .list-item {
      display: flex;
      justify-content: space-between
    }

    .gray {
      background-color: gray;
    }

    .checked {
      background-color: red
    }

  </style>
</head>

<body>
  <div id='root'>
    <!-- <div> -->
    <!-- ? 自闭和 -->
    <headerinput @addtask='addTask'></headerinput>
    <!-- </div> -->

    <listitem v-for='(item,index) in list' :item='item' :index='index' :key='item.key' @check='check' @remove='remove'>
    </listitem>
  </div>

  <script>
    let headerInput = {
      template: `
                <div>
                    <input type="text" v-model='value' @keyup.13='addTask'><button @click='addTask'>add</button>
                </div>
            `,
      data() {
        return {
          value: ''
        }
      },
      methods: {
        addTask() {
          if (this.value) {
            this.$emit('addtask', this.value);
            this.value = '';
          }
        }
      }
    }

    let listItem = {
      template: `
                <div
                    :class='["list-item", { checked:item.checked } , { gray: index%2==0 }]'
                    @click='check'
                    :key='item.key'
                >
                    <div>{{ item.name }} </div>
                    <div @click.stop='remove'>x</div>
                </div>
            `,
      props: ['item', 'index'],
      methods: {
        check() {
          this.$emit('check', this.index)
        },
        remove() {
          this.$emit('remove', this.index)
        }
      }
    }

    let vm = new Vue({
      el: '#root',
      components: {
        listitem: listItem,
        headerinput: headerInput
      },
      data: function () {
        return {
          list: [{
              name: 'task1',
              checked: false,
              key: Math.random()
            },
            {
              name: 'task2',
              checked: false,
              key: Math.random()
            }
          ] // 任务列表
        }
      },
      methods: {
        addTask(value) {
          this.list.push({
            name: value,
            checked: false,
            key: Math.random()
          })
        },
        check(index) {
          this.list[index].checked = !this.list[index].checked;
        },
        remove(index) {
          this.list.splice(index, 1)
        }
      },
      computed: {

      }
    })

  </script>
</body>

</html>
